package com.nescafe.nescafepromo.entity;

import java.text.ParseException;
import java.util.Date;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.nescafe.nescafepromo.model.GaisanoBranch;
import com.nescafe.nescafepromo.util.FormatUtil;

public class Purchase extends NPEntity {

	public static final String RECEIPT_DATE_FIELD = "receiptTime";
	public static final String BRANCH_FIELD = "branch";
	public static final String EMAIL_FIELD = "email";
	public static final String AMOUNT_FIELD = "amount";
	public static final String POINTS_FIELD = "points";

	private String receiptNo = null;
	private long receiptDate = -1;
	private long branch = -1;
	private String email = null;
	private double amount = 0;
	private long points = 0;
	private Key parent = null;

	public Purchase(String receiptNo, Key parentKey) {
		this.receiptNo = receiptNo;
		parent = parentKey;
	}

	public Purchase(Entity entity) {
		this.receiptNo = entity.getKey().getName();
		this.receiptDate = (Long) entity.getProperty(RECEIPT_DATE_FIELD);
		this.branch = (Long) entity.getProperty(BRANCH_FIELD);
		this.email = (String) entity.getProperty(EMAIL_FIELD);
		this.amount = (Double) entity.getProperty(AMOUNT_FIELD);
		this.points = (Long) entity.getProperty(POINTS_FIELD);
		this.parent = entity.getParent();
	}

	public void setReceiptNo(String receiptNo) {
		this.receiptNo = receiptNo;
	}

	public String getReceiptNo() {
		return receiptNo;
	}

	public void setReceiptDate(int receiptDate) {
		this.receiptDate = receiptDate;
	}

	public long getReceiptDate() {
		return receiptDate;
	}

	public void setBranch(int branch) {
		this.branch = branch;
	}

	public long getBranch() {
		return branch;
	}

	public String getBranchName() {
		return GaisanoBranch.fromCode((int) branch).getName();
	}

	public String getDisplayReceiptDate() {
		String displayDate = "";
		try {
			Date d = FormatUtil.dbDateFormat.parse(String.valueOf(receiptDate));
			if (d != null) {
				displayDate = FormatUtil.displayDateFormt.format(d);
			}
		} catch (ParseException e) {

		}
		return displayDate;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getEmail() {
		return email;
	}

	public void setAmount(double amount) {
		this.amount = amount;
	}

	public double getAmount() {
		return amount;
	}

	public void setPoints(int points) {
		this.points = points;
	}

	public long getPoints() {
		return points;
	}

	@Override
	public Entity toEntity() {
		Entity e = new Entity(EntityType.PURCHASE.getKind(), receiptNo, parent);
		e.setProperty(RECEIPT_DATE_FIELD, receiptDate);
		e.setProperty(BRANCH_FIELD, branch);
		e.setProperty(EMAIL_FIELD, email);

		e.setUnindexedProperty(AMOUNT_FIELD, amount);
		e.setUnindexedProperty(POINTS_FIELD, points);
		return e;
	}
}
